package com.jrzh.mvc.convert.sys;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.stereotype.Component;

import com.jrzh.common.exception.ProjectException;
import com.jrzh.common.tools.CollectionTools;
import com.jrzh.common.utils.ReflectUtils;
import com.jrzh.framework.base.convert.BaseConvertI;
import com.jrzh.mvc.model.sys.ConfigModel;
import com.jrzh.mvc.view.sys.ConfigView;

@Component("configConvert")
public class ConfigConvert implements BaseConvertI<ConfigModel, ConfigView>{

	public ConfigModel addConvert(ConfigView view) throws ProjectException {
		ConfigModel model = new ConfigModel();
		ReflectUtils.copySameFieldToTarget(view, model);
		return model;
	}

	public ConfigModel editConvert(ConfigView view, ConfigModel model)
			throws ProjectException {
		model.setValue(view.getValue());
		return model;
	}

	public ConfigView convertToView(ConfigModel model) throws ProjectException {
		ConfigView view = new ConfigView();
		ReflectUtils.copySameFieldToTarget(model, view);
		return view;
	}
	
	public ConfigView convertToTree(ConfigView view) throws ProjectException {
		view.setIsLeaf(CollectionTools.isNotBlank(view.getGroupList()));
		view.setLevel(CollectionTools.isNotBlank(view.getGroupList()) ? 2 : 1);
		view.setExpanded(true);
		return view;
	}
	
	public List<ConfigView> convertToTreeGrid(List<ConfigView> list) throws ProjectException {
		List<ConfigView> treeList = new ArrayList<ConfigView>();
		if(CollectionTools.isNotBlank(list)){
			for(ConfigView root : list){
				root.setId(UUID.randomUUID().toString());
				root.setName(root.getGroup());
				root.setIsLeaf(false);
				root.setLevel(1);
				root.setExpanded(false);
				treeList.add(root);
				List<ConfigView> groupList = root.getGroupList();
				if(CollectionTools.isNotBlank(groupList)){
					for(ConfigView child : groupList){
						child.setParentId(root.getId());
						child.setIsLeaf(true);
						child.setLevel(2);
						child.setExpanded(false);
						treeList.add(child);
					}
				}
			}
		}
		return treeList;
	}
}
